package com.gkoudai.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gkoudai.open.platform.client.SocketIoClient;
import com.gkoudai.open.platform.entry.SocketResponseBean;
import com.gkoudai.open.platform.handler.DataHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : Amater
 * @date : 2024/10/28 21:00
 */
@Slf4j
@Component
public class DataHandlers implements DataHandler {
    private final NewsService newsService;

    @Autowired
    public DataHandlers(NewsService newsService) {
        this.newsService = newsService;
    }

    @Override
    public void connectError(Object... objects) {
        log.info("connectError" + JSON.toJSONString(objects));
    }

    @Override
    public void connect(String connectMsg) {
        log.info("connect" + connectMsg);
    }

    @Override
    public void disconnect(Object... objects) {
        log.error("disconnect" + JSON.toJSONString(objects));
    }

    @Override
    public void quotesResponseHandler(String quoteResponse) {
        log.info("quotesResponseHandler:" + quoteResponse);
    }

    @Override
    public void subscribeQuoteResponseHandler(String response) {
        log.info(response);
    }

    @Override
    public void subscribeNewsResponseHandler(String response) {
        if (StringUtils.isBlank(response)) {
            return;
        }
        JSONObject responseObject = JSON.parseObject(response);
        if ("subscribeNews".equals(responseObject.get("type"))) {
            log.info("订阅资讯结果响应:{}", response);
            newsService.subscriptionNewsResponse(responseObject.toJavaObject(SocketResponseBean.class));
        }else {
            newsService.NewsResponse(responseObject);
        }



    }

    @Override
    public void subscribeStockQuoteResponseHandler(String response) {
        log.info(response);
    }

    @Override
    public boolean beforeReconnect(SocketIoClient socketIoClient) {
        log.info("beforeReconnect");
        //此处为自动重连前,返回true会继续进行重连,返回false则中断本次重连
        return true;
    }

    @Override
    public void afterReconnect(SocketIoClient socketIoClient) {
        log.info("afterReconnect");
        //此处为自动重连结束
    }

    @Override
    public void subscribeNewFuturesQuoteListener(String response) {
        log.info("subscribeNewFuturesQuoteListener:{}", response);
    }

    @Override
    public void newFuturesQuoteDataListener(String response) {
        log.info("newFuturesQuoteDataListener:{}", response);
    }
}
